#!/bin/bash

PATH=$PATH:/usr/bin:/usr/local/bin
pidfile="/var/run/nstat2-update.run"
trafdir="/var/traffic"
counter_pid="/var/run/ulog-acctd.pid"
counter_file="/var/log/ulog-acctd/account.log"
counter_name="ulog-acctd"
logfile="/var/traffic/ip.log"
counter_tmpfile="/var/tmp/ulog-traffic.tmp"
nstat_dir="/home/kreved/soft-svn/nstat/v2/nstat"

starttime=`date +%s`

# Сегодяшний день
day="`date +%Y-%m-%d`"
# Текущий год
year="`date +%Y`"
# Текущий месяц
month="`date +%m`"
curr_time="`date +%H:%M:%S`"

##################################
##################################
##################################

if [ -e ${pidfile} ]
then
 if kill -0 `cat ${pidfile}`
 then
  date >&2
  echo "I'm already running now... try later, please." >&2
  exit 1
 fi
 date >&2
 echo "Invalid pidfile? ${pidfile}" >&2
fi

echo $$ >${pidfile}

if !(kill -s SIGTSTP `cat ${counter_pid}`)
then
 echo "${counter_name} is not running?">&2; exit 1
else
 echo -n "Wait for ${counter_name}... "
 sleep 1
 echo "done"
 mv ${counter_file} ${counter_tmpfile}
 kill -s SIGCONT `cat ${counter_pid}`
fi

mkdir -p ${trafdir}
traflogfile="${trafdir}/${day}.log"

echo `wc -ml ${counter_tmpfile}`

cat ${counter_tmpfile} >> ${traflogfile}


cd ${nstat_dir}
echo -n 'Run update script: '
su www-data -c "./manage.py parselog" < ${counter_tmpfile}
su www-data -c "./manage.py checkusers" < ${counter_tmpfile}

# Очищаем файл c логами
rm -f ${counter_tmpfile}

finishtime=`date +%s`

let dt=$finishtime-$starttime >/dev/null
ndt="[$day $curr_time]: executed $dt seconds."
echo "Finished after $dt seconds."
echo $ndt >>${logfile}
rm ${pidfile}

